<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Listener;

use App\Lib\Consul\Agent;
use App\Lib\Consul\ServiceConfig;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Bean\BeanFactory;
use Swoft\Consul\Exception\ClientException;
use Swoft\Consul\Exception\ServerException;
use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Http\Server\HttpServer;
use Swoft\Log\Helper\CLog;
use Swoft\Server\SwooleEvent;

/**
 * Class RegisterServiceListener
 *
 * @since 2.0
 *
 * @Listener(event=SwooleEvent::START)
 */
class RegisterServiceListener implements EventHandlerInterface
{
    /**
     * @Inject()
     *
     * @var Agent
     */
    private $agent;

    /**
     * @param EventInterface $event
     */
    public function handle(EventInterface $event): void
    {
        //本地进行注册，其他环境都不注册
        if(env('APP_ENV', 'local') === 'local') {
            /** @var HttpServer $httpServer */
            $httpServer = $event->getTarget();

            /** @var ServiceConfig $ServiceConfig */
            $ServiceConfig = BeanFactory::getBean("ServiceConfig");
            $service = [
                'ID' => $ServiceConfig->getUuid(),
                'Name' => $ServiceConfig->getName(),
                'Tags' => $ServiceConfig->getTags(),
                'Address' => $ServiceConfig->getAddress(),
                'Port' => $ServiceConfig->getPort(),
                'Meta' => $ServiceConfig->getMetas(),
                'EnableTagOverride' => false,
                "Check" => [
                    "tcp" => $ServiceConfig->getAddress() . ':' . $ServiceConfig->getPort(),
                    "Interval" => "10s",
                    "Timeout" => "5s",
                ],
                'Weights' => [
                    'Passing' => 10,
                    'Warning' => 1
                ]
            ];

            // Register
            try {
                $this->agent->registerService($service);
            } catch (ClientException $e) {
                // consul 请求异常 链接成功但是请求参数或者请求格式错误
                CLog::error('consul 请求异常 链接成功但是请求参数或者请求格式错误！');
                $httpServer->stop();
                return;
            } catch (ServerException $e) {
                // consul IP地址链接不到
                CLog::error('consul IP地址或端口错误，链接不到服务！');
                $httpServer->shutdown();
                return;
            }
            CLog::info('Swoft http register service success by consul!');
        }
    }
}
